#!/usr/bin/env python
# encoding: utf-8
# Date: 2017/2/4 下午1:16
# file: mqtt_client.py
# Email: wangjian2254@icloud.com
# Author: 王健
import random

import paho.mqtt.client as mqtt
import settings

from util.jsonresult import get_result

MQTT_SERVER_REQUEST = 'web_api_request'
MQTT_SERVER_RESPONSE = 'web_api_response'
MQTT_SERVER_OPC_EVENT = 'opc_event'
MQTT_SERVER_FILE_SEND = 'file_send'
MQTT_SERVER_FILE_GET = 'file_get'
MQTT_SERVER_FILE_RESULT = 'file_send_response'

global_gateway_client = None
global_gateway_client_id = '%s-%s' % (
    settings.CURRENT_APP[0], "".join(random.choice("0123456789ADCDEF") for x in range(23 - 5)))

global_my_client = None
global_my_client_id = '%s-%s' % (
    settings.CURRENT_APP[0], "".join(random.choice("0123456789ADCDEF") for x in range(23 - 5)))


# The callback for when the client receives a CONNACK response from the server.


def push_message(client, topic, msg):
    import time
    # time.sleep(i%5)
    client.publish("$SYS/", "2121%s")


def print_message(client, msg):
    import threading

    thread = threading.current_thread()
    print thread.getName()
    print(msg.topic + " " + str(msg.payload))

    from django.test import Client

    web_client = Client()
    import json
    data = json.loads(msg.payload)
    import time
    timeline = int(time.time() * 1000)
    try:
        response = web_client.post(data['route'], data['parms'])
        client.publish('web_api_response/%s' % data['callid'], response.content)

        if hasattr(response, 'json'):
            print data['route'], ':', response.json['status_code'], ':', int(time.time() * 1000) - timeline

    except Exception as e:
        client.publish('web_api_response/%s' % data['callid'], get_result(False, u'服务器错误').content)
        raise e


def on_connect(client, userdata, flags, rc):
    # print("Connected with result code " + str(rc))
    print('%s Connected with result code  %s' % (client._client_id, str(rc)))

    client.subscribe("crane/#")


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    import thread

    if msg.topic.find(MQTT_SERVER_REQUEST) >= 0:
        thread.start_new_thread(print_message, (client, msg))
    # elif msg.topic.find(MQTT_SERVER_OPC_EVENT) >= 0:
    #     from production_manage.mqtt_opc_event import production_opc_event
    #     thread.start_new_thread(production_opc_event, (client, msg))
    # elif msg.topic.find(MQTT_SERVER_FILE_GET) >= 0:
    #     from nsbcs.mqtt_file_tools import get_file_data_by_path
    #     thread.start_new_thread(get_file_data_by_path, (client, msg))
    # elif msg.topic.find(MQTT_SERVER_FILE_SEND) >= 0:
    #     from nsbcs.mqtt_file_tools import upload_file_data_by_fileid
    #     thread.start_new_thread(upload_file_data_by_fileid, (client, msg))
    # elif msg.topic.find(MQTT_SERVER_RESPONSE) >= 0:
    #     from im_commend import mqtt_callback_response
    #     thread.start_new_thread(mqtt_callback_response, (client, msg.topic.split('/')[-1], str(msg.payload)))




def on_disconnect(client, userdata, rc):
    print '%s disconnect……' % client._client_id
    import time
    print 'gateway sleep 5'
    time.sleep(5)
    client.reconnect()


def mqtt_gateway_client_run(client_type='', on_message_fun=None):
    global global_gateway_client
    try:
        global_gateway_client = mqtt.Client('%s%s' % (client_type, global_gateway_client_id))

        global_gateway_client.on_connect = on_connect
        if on_message_fun:
            global_gateway_client.on_message = on_message_fun
        else:
            global_gateway_client.on_message = on_message
        global_gateway_client.on_disconnect = on_disconnect
        # global_client.username_pw_set("guest", "guest")
        global_gateway_client.username_pw_set(settings.CURRENT_APP[0],
                                              str('%s,%s,%s' % (
                                                  settings.CURRENT_APP[1], settings.CURRENT_APP[2], client_type)))

        global_gateway_client.connect(settings.LIYU_GATEWAY_HOST, settings.LIYU_GATEWAY_PORT, 60)

        print 'gateway start……'
        global_gateway_client.loop_forever()
    except Exception as e:
        global_gateway_client = None
        import time
        print 'gateway sleep 5'
        time.sleep(5)
        import thread
        thread.start_new_thread(mqtt_gateway_client_run, ('', on_message_fun))


